package com.transaction.seataorder.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author ausu
 * @version 1.0
 * @description: TODO
 * @date 2023/1/10 16:07
 */
@Component
@Slf4j
public class RedisUtil {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public boolean setEx(String key,String value,Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.set(key,value);
            redisTemplate.expire(key,expireTime, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        return result;
    }

    public boolean isExit(String key) {
        return redisTemplate.hasKey(key);
    }

    public boolean remove(String key) {
        if (isExit(key)) {
            redisTemplate.delete(key);
            return true;
        }
        return false;
    }
}
